/*
 * Copyright (c) 2023 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "wfd_callback_napi.h"
#include "common/sharing_log.h"
#include "wfd_napi.h"

namespace OHOS {
namespace Sharing {

void WfdCallbackNapi::SaveCallbackReference(const std::string &name, std::weak_ptr<AutoRef> ref)
{
    SHARING_LOGD("trace.");
    std::lock_guard<std::mutex> lock(mutex_);
    refMap_[name] = ref;
}

void WfdCallbackNapi::ClearCallbackReference(const std::string &name)
{
    SHARING_LOGD("trace.");
    std::lock_guard<std::mutex> lock(mutex_);
    // refMap_.clear();
    // 在unordered_map中查找指定名称的元素
    auto it = refMap_.find(name);

    // 如果找到了对应的元素
    if (it!= refMap_.end())
    {
        // 从unordered_map中删除该元素
        refMap_.erase(it);
    }
}

void WfdCallbackNapi::OnJsCallback(WfdJsCallback *jsCb)
{
    SHARING_LOGD("trace.");
    uv_loop_s *loop = nullptr;
    napi_get_uv_event_loop(env_, &loop);
    if (loop == nullptr) {
        delete jsCb;
        return;
    }

    uv_work_t *work = new (std::nothrow) uv_work_t;
    if (work == nullptr) {
        SHARING_LOGE("No memory.");
        delete jsCb;
        return;
    }

    work->data = reinterpret_cast<void *>(jsCb);

    int32_t ret = uv_queue_work(
        loop, work, [](uv_work_t *work) {},
        [](uv_work_t *work, int32_t status) {
            // Js Thread
            CHECK_AND_RETURN_LOG(work != nullptr, "work is nullptr.");
            WfdJsCallback *event = reinterpret_cast<WfdJsCallback *>(work->data);

            std::string request = event->callbackName;
            SHARING_LOGI("JsCallBack %{public}s, uv_queue_work start.", request.c_str());
            do {
                if (status == UV_ECANCELED) {
                    SHARING_LOGE("%{public}s canceled.", request.c_str());
                    break;
                }

                std::shared_ptr<AutoRef> ref = event->callback.lock();
                if (ref == nullptr) {
                    SHARING_LOGE("%{public}s AutoRef is nullptr.", request.c_str());
                    break;
                }

                napi_handle_scope scope = nullptr;
                napi_open_handle_scope(ref->env_, &scope);
                if (scope == nullptr) {
                    SHARING_LOGE("scope is nullptr.");
                    return;
                }

                napi_value jsCallback = nullptr;
                napi_status nstatus = napi_get_reference_value(ref->env_, ref->cb_, &jsCallback);
                if (nstatus != napi_ok || jsCallback == nullptr) {
                    SHARING_LOGE("%{public}s get reference value fail.", request.c_str());
                    break;
                }

                napi_value args[1] = {nullptr};
                event->jsResult->GetJsResult(ref->env_, args[0]);

                // Call back function
                napi_value result = nullptr;
                nstatus = napi_call_function(ref->env_, nullptr, jsCallback, 1, args, &result);

                napi_close_handle_scope(ref->env_, scope);
                if (nstatus != napi_ok) {
                    SHARING_LOGE("%{public}s fail to napi call function.", request.c_str());
                    break;
                }
            } while (0);

            SHARING_LOGI("JsCallBack %{public}s, uv_queue_work done.", request.c_str());
            delete event;
            delete work;
        });

    if (ret != 0) {
        SHARING_LOGE("Failed to execute libuv work queue.");
        delete jsCb;
        delete work;
    }
}

void WfdCallbackNapi::OnInfo(std::shared_ptr<BaseMsg> &msg)
{
    SHARING_LOGD("trace.");
    CHECK_AND_RETURN_LOG(msg != nullptr, "msg is nullptr.");

    SHARING_LOGI("msg: %{public}d.", msg->GetMsgId());
    switch (msg->GetMsgId()) {
        case WfdErrorMsg::MSG_ID: {
            auto data = std::static_pointer_cast<WfdErrorMsg>(msg);
            OnError(data->mac, data->errorCode, data->message);
            break;
        }
        // case WfdConnectionChangedMsg::MSG_ID: {
        //     auto data = std::static_pointer_cast<WfdConnectionChangedMsg>(msg);
        //     ConnectionInfo info;
        //     info.ip = data->ip;
        //     info.mac = data->mac;
        //     info.state = static_cast<ConnectionState>(data->state);
        //     info.surfaceId = data->surfaceId;
        //     info.deviceName = data->deviceName;
        //     info.primaryDeviceType = data->primaryDeviceType;
        //     info.secondaryDeviceType = data->secondaryDeviceType;

        //     if (napi_) {
        //         napi_->OnStateChanged(info.mac, info.state);
        //     }

        //     OnDeviceStateChanged(info);
        //     break;
        // }
        // case WfdDecoderAccelerationDoneMsg::MSG_ID: {
        //     auto data = std::static_pointer_cast<WfdDecoderAccelerationDoneMsg>(msg);
        //     OnAccelerationDone(std::to_string(data->surfaceId));
        //     break;
        // }
        // case WfdSurfaceFailureMsg::MSG_ID: {
        //     auto data = std::static_pointer_cast<WfdSurfaceFailureMsg>(msg);
        //     OnError(data->mac, ERR_SURFACE_FAILURE, "On Dev Codec Surface Failure");
        //     break;
        // }
        case WfdSourceDeviceFoundMsg::MSG_ID: {  // 返回设备信息列表
            auto data = std::static_pointer_cast<WfdSourceDeviceFoundMsg>(msg);
            OnDeviceFound(data->deviceInfos);
            break;
        }
        case WfdSinkDeviceRequestMsg::MSG_ID: {  // 返回设备请求列表
            auto data = std::static_pointer_cast<WfdSinkDeviceRequestMsg>(msg);
            OnDeviceRequest(data->deviceRequestInfos);
            break;
        }
        default:
            SHARING_LOGI("none process case.");
            break;
    }
}

void WfdCallbackNapi::OnError(std::string deviceId, int32_t errorCode, std::string msg)
{
    SHARING_LOGD("trace.");
    std::lock_guard<std::mutex> lock(mutex_);
    if (refMap_.find("error") == refMap_.end()) {
        SHARING_LOGW("can not find error callback!");
        return;
    }

    WfdJsCallback *cb = new (std::nothrow) WfdJsCallback();
    CHECK_AND_RETURN_LOG(cb != nullptr, "cb is nullptr.");

    cb->callback = refMap_.at("error");
    cb->callbackName = "error";
    cb->jsResult = std::make_unique<WfdErrorJsResult>(errorCode, msg, deviceId);

    OnJsCallback(cb);
    SHARING_LOGD("error out.");
}

// 监听到的设备列表返回js
void WfdCallbackNapi::OnDeviceFound(std::vector<WfdCastDeviceInfo> &info)
{
    SHARING_LOGD("trace.");
    std::lock_guard<std::mutex> lock(mutex_);
    if (refMap_.find("deviceFound") == refMap_.end()) {
        SHARING_LOGW("can not find deviceFound callback!");
        return;
    }

    WfdJsCallback *cb = new (std::nothrow) WfdJsCallback();
    CHECK_AND_RETURN_LOG(cb != nullptr, "cb is nullptr.");

    cb->callback = refMap_.at("deviceFound");
    cb->callbackName = "deviceFound";
    cb->jsResult = std::make_unique<WfdSourceDeviceFoundJsResult>(info);

    OnJsCallback(cb);
    SHARING_LOGD("deviceFound out.");
}

void WfdCallbackNapi::OnDeviceRequest(std::vector<WfdCastDeviceRequestInfo> &info)
{
    SHARING_LOGD("trace.");
    std::lock_guard<std::mutex> lock(mutex_);
    if (refMap_.find("deviceRequest") == refMap_.end()) {
        SHARING_LOGW("can not find deviceRequest callback!");
        return;
    }

    WfdJsCallback *cb = new (std::nothrow) WfdJsCallback();
    CHECK_AND_RETURN_LOG(cb != nullptr, "cb is nullptr.");

    cb->callback = refMap_.at("deviceRequest");
    cb->callbackName = "deviceRequest";
    cb->jsResult = std::make_unique<WfdSinkeDeviceRequestJsResult>(info);

    OnJsCallback(cb);
    SHARING_LOGD("deviceRequest out.");
}

} // namespace Sharing
} // namespace OHOS